package com.shine.app.widget.rangebar;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.util.TypedValue;

public class Bar {

	private final Paint paint;
	private final float leftX;
	private final float rightX;
	private final float y;
	private int numSegments;
	private float tickDistance;
	private final float tickHeight;
	private final float tickStartY;
	private final float tickEndY;

	public Bar(Context ctx, float x, float y, float length, int tickCount,
			float tickHeightDP, float BarWeight, int BarColor) {
		this.leftX = x;
		this.rightX = x + length;
		this.y = y;
		this.numSegments = tickCount - 1;
		this.tickDistance = length / numSegments;
		this.tickHeight = TypedValue.applyDimension(
				TypedValue.COMPLEX_UNIT_DIP, tickHeightDP, ctx.getResources()
						.getDisplayMetrics());
		this.tickStartY = y - tickHeight / 2f;
		this.tickEndY = y + tickHeight / 2f;
		this.paint = new Paint();
		this.paint.setColor(BarColor);
		this.paint.setStrokeWidth(BarWeight);
		this.paint.setAntiAlias(true);
	}

	void draw(Canvas canvas) {
		canvas.drawLine(leftX, y, rightX, y, paint);
		drawTicks(canvas);
	}

	float getLeftX() {
		return leftX;
	}

	float getRightX() {
		return rightX;
	}

	float getNearestTickCoordinate(Thumb thumb) {
		final int nearestTickIndex = getNearestTickIndex(thumb);
		final float nearestTickCoordinate = leftX
				+ (nearestTickIndex * tickDistance);
		return nearestTickCoordinate;
	}

	int getNearestTickIndex(Thumb thumb) {
		final int nearestTickIndex = (int) ((thumb.getX() - leftX + tickDistance / 2f) / tickDistance);
		return nearestTickIndex;
	}

	void setTickCount(int tickCount) {
		final float barLength = rightX - leftX;
		numSegments = tickCount - 1;
		tickDistance = barLength / numSegments;
	}

	private void drawTicks(Canvas canvas) {
		for (int i = 0; i < numSegments; i++) {
			final float x = i * tickDistance + leftX;
			canvas.drawLine(x, tickStartY, x, tickEndY, paint);
		}
		canvas.drawLine(rightX, tickStartY, rightX, tickEndY, paint);
	}
}
